from .models import Vocation
from .serializers import VocationSerializer
from rest_framework.response import Response
from rest_framework import generics

class vocationClass(generics.GenericAPIView):
    queryset = Vocation.objects.all().order_by('id')
    serializer_class = VocationSerializer

    # GET请求
    def get(self, request):
        # 获取请求参数
        job = request.GET.get('job', '')
        data = self.get_queryset()
        if job:
            data = data.filter(job=job)
        # 数据分页处理
        data = self.paginate_queryset(data)
        serializer = self.get_serializer(data, many=True)
        # 返回分页的前一页、后一页和总数据量
        res = self.get_paginated_response(serializer.data)
        # 返回对象Response由Django Rest Framework实现
        return res

    # POST请求
    def post(self, request):
        # 获取请求数据
        id = request.data.get('id', 0)
        operation = self.get_queryset().filter(id=id).first()
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        if operation:
            # 修改数据
            serializer.update(operation, request.data)
        else:
            # 新增数据
            serializer.save()
        # 返回对象Response由Django Rest Framework实现
        return Response(serializer.data)
